package com.yang.controller;

import com.yang.entity.OrderDetail;
import com.yang.entity.Result;
import com.yang.interceptors.LogExecutionTime;
import com.yang.service.OrderService;
import com.yang.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
     * 创建订单
     *
     * @param orderDetails 订单详情
     * @return 订单id
     */
    @PostMapping("/createOrder")
    @LogExecutionTime
    public Result createOrder(@RequestBody List<OrderDetail> orderDetails) {
        long res = orderService.createOrder(orderDetails);
        if (res == 1) {
            return Result.error("创建失败，有未支付的订单");
        } else {
            return Result.success(res);
        }
    }

    @PostMapping("/updateOrder")
    @LogExecutionTime
    public Result updateOrder(@RequestParam int status, @RequestParam int ordersId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        // TODO 这里的userId后续可以换成long类型
        int userId = (int) map.get("userId");
        orderService.updateOrderStatus(status, ordersId, userId);
        return Result.success();

    }

    /**
     * 修改订单的收货地址
     *
     * @param addressId     收货地址id
     * @param orderDetailId 订单id
     * @return Result
     */
    @PostMapping("/updateAddressOfOrders")
    @LogExecutionTime
    public Result updateAddressOfOrders(@RequestParam List<Integer> orderDetailId, @RequestParam Integer addressId) {
        System.out.println(orderDetailId);
        System.out.println(addressId);
        if (orderService.updateAddressOfOrders(orderDetailId, addressId) >= 1) {
            return Result.success();
        } else {
            return Result.error("修改失败");
        }
    }

    @GetMapping("/getOrders")
    @LogExecutionTime
    public Result getOrders(@RequestParam Integer pageNum) {
        List<OrderDetail> orderDetails = orderService.getOrders(pageNum);
        if (orderDetails == null) {
            return Result.error("获取订单失败，页码超出范围");
        }
        return Result.success(orderDetails);
    }

}
